package com.cyj.dream.admin.persistence.manager.systems;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyj.dream.admin.contacts.enums.IsDeleteEnum;
import com.cyj.dream.core.constant.users.UserContext;
import com.cyj.dream.core.constant.users.UserInfoDTO;
import com.cyj.dream.admin.model.request.SysRoleQueryRequest;
import com.cyj.dream.admin.model.system.SysRole;
import com.cyj.dream.admin.model.system.SysUserRole;
import com.cyj.dream.admin.persistence.service.ITbSysRoleService;
import com.cyj.dream.admin.service.system.SysUserRoleService;
import com.cyj.dream.admin.util.IsEmptyUtils;
import com.cyj.dream.core.constant.enums.ResultCode;
import com.cyj.dream.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 系统角色管理器类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.dream.DreamChardonnay.persistence.manager.systems
 * @Author: ChenYongJia
 * @CreateTime: 2021-04-21 09:53
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Component
public class SysRoleManager {

    @Autowired
    private ITbSysRoleService iTbSysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 查询角色信息列表
     *
     * @param page                数据
     * @param SysRoleQueryRequest 请求入参参数
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.dream.DreamChardonnay.model.system.SysRole>
     * @date 2021/4/21 10:04
     * @author ChenYongJia
     * @version 1.0
     */
    public Page<SysRole> list(Page<SysRole> page, SysRoleQueryRequest SysRoleQueryRequest) {
        log.info("进入 SysRoleManager 查询角色信息列表，参数 page：{}，参数 param：{}", JSONObject.toJSONString(page), SysRoleQueryRequest);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();

        if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest)) {
            // 角色名称
            if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest.getSysRoleName())) {
                wrapper.like(SysRole::getSysRoleName, SysRoleQueryRequest.getSysRoleName());
            }
            // 角色分组
            if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest.getSysRoleGroup())) {
                wrapper.like(SysRole::getSysRoleGroup, SysRoleQueryRequest.getSysRoleGroup());
            }
            // 角色类型
            if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest.getSysRoleType())) {
                wrapper.eq(SysRole::getSysRoleType, SysRoleQueryRequest.getSysRoleType());
            }
            // 角色权限名称
            if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest.getSysRoleTrueName())) {
                wrapper.like(SysRole::getSysRoleTrueName, SysRoleQueryRequest.getSysRoleTrueName());
            }
            // 角色状态(0:启用,1:禁用)
            if (!IsEmptyUtils.isEmpty(SysRoleQueryRequest.getSysRoleStatus())) {
                wrapper.eq(SysRole::getSysRoleStatus, SysRoleQueryRequest.getSysRoleStatus());
            }
        }

        wrapper.eq(SysRole::getSysRoleStatus, 0);
        wrapper.orderByDesc(true, SysRole::getSysRoleWeight);

        return iTbSysRoleService.page(page, wrapper);
    }

    /**
     * 根据角色id或者角色权限名称查询角色
     *
     * @param sysRole 角色对象
     * @return com.dream.DreamChardonnay.model.system.SysRole
     * @date 2021/5/6 9:36
     * @author ChenYongJia
     * @version 1.0
     */
    public SysRole selectBySysRoleIdOrSysRoleTrueName(SysRole sysRole) {
        log.info("进入 SysRoleManager 根据角色id或者角色权限名称查询角色，参数 sysRole：{}", JSONObject.toJSONString(sysRole));
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        if (!IsEmptyUtils.isEmpty(sysRole.getDreamId())) {
            wrapper.eq(SysRole::getDreamId, sysRole.getDreamId());
        }
        if (!IsEmptyUtils.isEmpty(sysRole.getSysRoleTrueName())) {
            wrapper.like(SysRole::getSysRoleTrueName, sysRole.getSysRoleTrueName());
        }
        if (!IsEmptyUtils.isEmpty(sysRole.getSysRoleName())) {
            wrapper.like(SysRole::getSysRoleName, sysRole.getSysRoleName());
        }

        wrapper.eq(SysRole::getSysRoleStatus, IsDeleteEnum.DIS_DELETE.getCode());

        return iTbSysRoleService.getOne(wrapper);
    }

    /**
     * 添加角色信息
     *
     * @param sysRole 角色对象
     * @return boolean
     * @date 2021/4/21 9:58
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean addRoleInfo(SysRole sysRole) {
        log.info("进入 SysRoleManager 添加角色信息方法，参数为：{}", JSONObject.toJSONString(sysRole));

        UserInfoDTO userInfoDto = UserContext.get();
        if (!IsEmptyUtils.isEmpty(this.selectBySysRoleIdOrSysRoleTrueName(sysRole))) {
            log.error("角色名已存在，请重新填写表单后提交");
            throw new BizException(ResultCode.ROLE_HAS_EXISTED);
        }

        sysRole.setCreateTime(LocalDateTime.now());
        sysRole.setCreateUserId(userInfoDto.getSysUserId());
        return iTbSysRoleService.save(sysRole);

    }

    /**
     * 修改角色信息
     *
     * @param sysRole 角色对象
     * @return boolean
     * @date 2021/4/21 9:58
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean updRoleInfo(SysRole sysRole) {
        log.info("进入 SysRoleManager 修改角色信息方法，参数为：{}", JSONObject.toJSONString(sysRole));

        UserInfoDTO userInfoDto = UserContext.get();

        sysRole.setUpdateTime(LocalDateTime.now());
        sysRole.setUpdateUserId(userInfoDto.getSysUserId());
        return iTbSysRoleService.updateById(sysRole);

    }

    /**
     * 删除角色信息
     *
     * @param sysRole 角色对象
     * @return boolean
     * @date 2021/4/21 9:58
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean delRoleInfo(List<SysRole> sysRole) {
        log.info("进入 SysRoleManager 删除角色信息方法，参数为：{}", JSONObject.toJSONString(sysRole));

        UserInfoDTO userInfoDto = UserContext.get();
        SysUserRole sysUserRole = new SysUserRole();
        sysRole.stream().forEach(item -> {
            sysUserRole.setSysRoleId(item.getDreamId());
            if (IsEmptyUtils.isEmpty(sysUserRoleService.selectSysUserRoleList(sysUserRole))) {
                item.setSysRoleStatus(1);
                item.setUpdateTime(LocalDateTime.now());
                item.setUpdateUserId(userInfoDto.getSysUserId());
            } else {
                log.error("出现错误：当前所选定角色已设置给用户，请检查移除后在进行删除操作！");
                throw new BizException(ResultCode.ERROR);
            }
        });
        return iTbSysRoleService.updateBatchById(sysRole);
    }

}
